package com.video.service.task.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.video.commons.task.TaskStatusUtil;
import com.video.commons.utils.StringUtil;
import com.video.entity.ClientMsg;
import com.video.entity.Task;
import com.video.entity.Webcon;
import com.video.mapper.TaskMapper;
import com.video.service.client.IClientService;
import com.video.service.task.ITaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements ITaskService {

    @Autowired
    private TaskStatusUtil taskStatusUtil;

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private IClientService clientService;

    /**
     * 添加任务
     * @param task
     * @return
     */
    @Override
    @Transactional
    public int insert(Task task) {
        int result = taskMapper.insert(task);

        //保存任务同步添加redis状态信息
        taskStatusUtil.addTaskStatus(task);
        return result;
    }

    /**
     * 查询任务列表，根据分控账号
     * @param taskt
     * @param account
     * @param solution
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public List<Task> queryTaskList(Integer taskt, String account, String solution) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if(account != null){
            queryWrapper.eq("account", account);
        }
        queryWrapper.eq("taskt", taskt);
        if(taskt == 1){
            queryWrapper.eq("solution", StringUtil.isNotEmpty(solution) ? solution : "Default Solution");
        }
        return taskMapper.selectList(queryWrapper);
    }

    /**
     * 复制任务
     * @param taskid
     * @return
     */
    @Override
    @Transactional
    public Task copyTask(String taskid) {
        Task task = getByTaskId(taskid);
        if(task != null){
            task.setTaskid(UUID.randomUUID().toString());
            //调用当前业务进行保存
            this.insert(task);
        }
        return task;
    }

    @Override
    @Transactional(readOnly = true)
    public Task getByTaskId(String taskid) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("taskid", taskid);
        return taskMapper.selectOne(queryWrapper);
    }

    /**
     * 修改任务音量
     * @param taskid
     * @param volume
     * @return
     */
    @Override
    @Transactional
    public Task updateTaskVolume(String taskid, int volume, Integer looptype) {
        Task task = getByTaskId(taskid);
        task.setVolume(volume);

        if (looptype != null){
            task.setLooptype(looptype);
        }

        taskMapper.updateById(task);

        String users = task.getUsers();
        List<Integer> integers = JSON.parseArray(users, Integer.class);

        for (Integer integer : integers) {
            ClientMsg clientMsg = clientService.getById(integer);
            clientMsg.setVolume(volume + "");
            clientService.updateById(clientMsg);
        }

        return task;
    }

    /**
     * 根据任务id修改任务
     * @param task
     * @return
     */
    @Override
    public Task updateTaskByTaskId(Task task) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("taskid", task.getTaskid());
        taskMapper.update(task, queryWrapper);

        //查询最新的任务信息
        Task newTask = getByTaskId(task.getTaskid());

        //修改任务，同步任务状态到redis
        taskStatusUtil.addTaskStatus(newTask);

        return newTask;
    }

    /**
     * 根据方案和分控账号，查询对应的任务（定时音乐任务）
     * @param solution
     * @param account
     * @return
     */
    @Override
    public List<Task> queryBySolution(String solution, String account) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("solution", solution);
        if(account != null){
            queryWrapper.eq("account", account);
        }
        return taskMapper.selectList(queryWrapper);
    }

    /**
     * 根据分控账号和任务类型查询任务列表
     * @param account
     * @param taskt
     * @return
     */
    @Override
    public List<Task> queryByAccountAndTaskType(String account, int taskt) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if(account != null){
            queryWrapper.eq("account", account);
        }
        queryWrapper.eq("taskt", taskt);
        return taskMapper.selectList(queryWrapper);
    }

    /**
     * 修改制定任务的总持续时间
     * @param taskid
     * @param duration
     * @return
     */
    @Override
    @Transactional
    public int updateTaskDuration(String taskid, int duration) {
        Task task = getByTaskId(taskid);
        task.setDuration(duration);
        updateTaskByTaskId(task);
        return 1;
    }

    /**
     * 修改任务状态
     * @param taskid
     * @param status
     * @param startDate
     * @return
     */
    @Override
    @Transactional
    public int updateTaskStatus(String taskid, int status, String startDate) {

        Task task = getByTaskId(taskid);
        if(task == null){
            return 0;
        }

        if(task.getPlayOrder() == 3 && status == 2){
            //如果是一次性任务 并且 是停止命令
            //删除任务
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("taskid", task.getTaskid());
            taskMapper.delete(queryWrapper);

            return 1;
        } else if((task.getPlayOrder() == 1 || task.getPlayOrder() == 2) && status == 2 && startDate != null){
            //如果是每天任务 或者是 每周任务
            //更新任务的下次开始时间
            task.setStartDate(startDate);
            taskMapper.updateById(task);

            return 2;
        }
        return 0;
    }

    /**
     * 根据分控账号删除任务
     * @param account
     * @return
     */
    @Override
    @Transactional
    public int deleteByAccount(String account) {
        Map<String, Object> param = new HashMap<>();
        param.put("account", account);
        return taskMapper.deleteByMap(param);
    }

    /**
     * 所有指定 分控 下该 终端 的 任务关系，如果任务只包含该终端，则任务直接删除
     * @param uid
     * @return
     */
    @Override
    @Transactional
    public int deleteTaskByUid(Integer uid, Webcon webcon) {
        //查询跟该终端相关的任务
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.like("users", "%" + uid + "%");
        queryWrapper.eq("account", webcon.getAccount());
        List<Task> tasks = taskMapper.selectList(queryWrapper);

        //循环任务
        for (Task task : tasks) {
            //获得任务下的所有终端
            List<Integer> list = JSON.parseArray(task.getUsers(), Integer.class);
            //循环任务下的所有终端
            for (Integer taskUid : new ArrayList<>(list)) {
                if (taskUid.intValue() == uid.intValue()){
                    //如果只有这一个终端
                    if(list.size() == 1){
                        //直接删除任务
                        taskMapper.deleteById(task.getId());
                    } else {
                        //删除该任务与终端的关系
                        list.remove(taskUid);

                        //修改任务
                        task.setUsers(JSON.toJSONString(list));
                        taskMapper.updateById(task);
                    }

                    break;
                }
            }
        }

        return 1;
    }
}
